//
//  MetaMagicFeatController.m
//  This file is part of D&D Manager
//
//  Created by Matthew Hutton on 16/06/2007.
//
//
//D&D Manager, a D&D Character and battle management program.
//Copyright (C) 2007, Matthew Hutton
//
//This program is free software; you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation; either version 2 of the License, or (at your option) any later version.
//
//This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License for more details.
//
//You should have received a copy of the GNU General Public License along with this program; if not, write to:
//The Free Software Foundation, Inc.,
//51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA.


#import "MetaMagicFeatController.h"
#import "FeatActions.h"

@implementation MetaMagicFeatController
-(id)init{
	[super init];
	[NSBundle loadNibNamed:@"MetaMagicFeats"
					 owner:self];
	return self;
}
-(IBAction)addToChosenMetamagicFeats:(id)sender{
	NSManagedObject *feat=[availableFeats objectAtIndex:[allMetamagicFeats selectedRow]];
	[chosenFeats addObject:feat];
	[chosenFeats sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]];
	[chosenMetamagicFeats reloadData];
	[addToChosenButton setEnabled:NO];
	[removeFromChosenButton setEnabled:YES];
	//set cast level box.
	int featVal=[[feat valueForKey:@"spellLevelMod"] intValue];
	if([[feat valueForKey:@"spellKey"] isEqualToString:@"Caster Level"]){
		if([FeatActions xValueInUse:feat]){
			featVal=featVal+[[feat valueForKey:@"xValue"] intValue];
		}else{
			featVal=[FeatActions processValue:featVal
								   byModifier:[feat valueForKey:@"spellMod"]];
		}
	}
	[castAtLevel setIntValue:featVal+[castAtLevel intValue]];
}
-(IBAction)cancelMetamagicFeatWindow:(id)sender{
	[metamagicFeatWindow orderOut:sender];
	[NSApp endSheet:metamagicFeatWindow returnCode:1];
}
-(BOOL)checkWhetherFeatCanBeAdded:(NSManagedObject *)feat{
	int cCastAtLevel=[castAtLevel intValue];
	cCastAtLevel=cCastAtLevel+[[feat valueForKey:@"spellLevelMod"] intValue];
	if([[feat valueForKey:@"spellKey"] isEqualToString:@"Caster Level"]){
		if([FeatActions xValueInUse:feat]){
			cCastAtLevel=cCastAtLevel+[[feat valueForKey:@"xValue"] intValue];
		}else{
			cCastAtLevel=[FeatActions processValue:cCastAtLevel
										byModifier:[feat valueForKey:@"spellMod"]];
		}
	}	
	if(cCastAtLevel>maxCastLevel){
		return NO;
	}else{
		return YES;
	}
}
-(IBAction)continueMetamagicFeatWindow:(id)sender{
	[tempSpellClass setValue:[NSSet setWithArray:chosenFeats]
					  forKey:@"featsTemp"];
	int cal=[castAtLevel intValue];
	if([[[tempSpellClass valueForKey:@"spellClass"] valueForKey:@"level"] intValue]==cal){
		[tempSpellClass setValue:nil
						  forKey:@"castAtLevelTemp"];
	}else{
		[tempSpellClass setValue:[NSNumber numberWithInt:cal]
						  forKey:@"castAtLevelTemp"];
	}
	[metamagicFeatWindow orderOut:sender];
	[NSApp endSheet:metamagicFeatWindow returnCode:0];
}
-(void)displayMetamagicFeatScreenForTempSpellClass:(NSManagedObject *)tsc
									  modalDelegate:(NSObject *)delegateObject
									   endSelector:(SEL)endSelector
									modalForWindow:(NSWindow *)window{
	if(availableFeats==nil){
		availableFeats=[[NSMutableArray alloc] initWithCapacity:1];
	}
	if(chosenFeats==nil){
		chosenFeats=[[NSMutableArray alloc] initWithCapacity:1];
	}
	tempSpellClass=tsc;
	NSManagedObject *obj=[tempSpellClass valueForKey:@"character"];
	[availableFeats setArray:[[[obj valueForKey:@"feats"] allObjects] filteredArrayUsingPredicate:[NSPredicate predicateWithFormat:@"type==2 AND active==1"]]];
	[chosenFeats setArray:[[tsc valueForKey:@"featsTemp"] allObjects]];
	[availableFeats sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]];
	[chosenFeats sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]];
	int baseLevel;
	if([tsc valueForKey:@"castAtLevelTemp"]==nil){
		baseLevel=[[[tsc valueForKey:@"spellClass"] valueForKey:@"level"] intValue];
	}else{
		baseLevel=[[tsc valueForKey:@"castAtLevelTemp"] intValue];
	}
	NSManagedObject *aClass=[[tempSpellClass valueForKey:@"spellClass"] valueForKey:@"aClass"];
	if([[aClass valueForKey:@"divineSpell"] intValue]==-1){
		maxCastLevel=1;
		minCastLevel=9;
	}else{
		maxCastLevel=[[aClass valueForKey:@"minimumSpellLevel"] intValue];
		minCastLevel=[[aClass valueForKey:@"maximumSpellLevel"] intValue];
	}
	NSArray *spellLevels=[[obj valueForKey:@"spellLevel"] allObjects];
	int i;
	for(i=0;i<[spellLevels count];i++){
		NSManagedObject *spellLevel=[spellLevels objectAtIndex:i];
		if([[spellLevel valueForKey:@"spellsLeft"] intValue]>0){
			int currentLevel=[[spellLevel valueForKey:@"level"] intValue];
			if(currentLevel>maxCastLevel){
				maxCastLevel=currentLevel;
			}
			if(currentLevel<minCastLevel){
				minCastLevel=currentLevel;
			}
		}
	}
	[castAtLevel setIntValue:baseLevel];
	[allMetamagicFeats reloadData];
	[chosenMetamagicFeats reloadData];
	//NSLog(@"window=%@",window);
	//NSLog(@"metamagicFeatWindow=%@",metamagicFeatWindow);
	[NSApp beginSheet:metamagicFeatWindow
	   modalForWindow:window
		modalDelegate:delegateObject
	   didEndSelector:endSelector
		  contextInfo:tsc];
}
-(IBAction)removeFromChosenMetamagicFeats:(id)sender{
	NSManagedObject *removingFeat=[chosenFeats objectAtIndex:[chosenMetamagicFeats selectedRow]];
	[chosenFeats removeObjectAtIndex:[chosenMetamagicFeats selectedRow]];
	int featVal=[[removingFeat valueForKey:@"spellLevelMod"] intValue];
	if([[removingFeat valueForKey:@"spellKey"] isEqualToString:@"Caster Level"]){
		if([FeatActions xValueInUse:removingFeat]){
			featVal=featVal+[[removingFeat valueForKey:@"xValue"] intValue];
		}else{
			featVal=[FeatActions processValue:featVal
								   byModifier:[removingFeat valueForKey:@"spellMod"]];
		}
	}
	[castAtLevel setIntValue:[castAtLevel intValue]-featVal];
	[chosenFeats sortUsingDescriptors:[NSArray arrayWithObject:[[NSSortDescriptor alloc] initWithKey:@"name" ascending:YES]]];
	if([chosenFeats count]==0){
		[removeFromChosenButton setEnabled:NO];
	}
	NSManagedObject *feat=[availableFeats objectAtIndex:[allMetamagicFeats selectedRow]];
	if([chosenFeats containsObject:feat]){
		[addToChosenButton setEnabled:NO];
	}else{
		[addToChosenButton setEnabled:[self checkWhetherFeatCanBeAdded:feat]];
	}
	[chosenMetamagicFeats reloadData];
}

-(void)tableViewSelectionDidChange:(NSNotification *)aNotification{
	if([[aNotification object] isEqualTo:chosenMetamagicFeats]){
		if([chosenMetamagicFeats selectedRow]==-1){
			[removeFromChosenButton setEnabled:NO];
			[xValueTF setEnabled:NO];
			[xValueTF setStringValue:@"N/A"];
			[xValueTF setBackgroundColor:[NSColor colorWithDeviceRed:0.93
															   green:0.93
																blue:0.93
															   alpha:1.0]];
			return;
		}
		NSManagedObject *feat=[chosenFeats objectAtIndex:[chosenMetamagicFeats selectedRow]];
		if([FeatActions xValueInUse:feat]){
			[xValueTF setEnabled:YES];
			[xValueTF setIntValue:[[feat valueForKey:@"xValue"] intValue]];
			[xValueTF setBackgroundColor:[NSColor colorWithDeviceRed:1.0
															 green:1.0
															  blue:1.0
															 alpha:1.0]];
		}else{
			[xValueTF setEnabled:NO];
			[xValueTF setStringValue:@"N/A"];
			[xValueTF setBackgroundColor:[NSColor colorWithDeviceRed:0.93
															   green:0.93
																blue:0.93
															   alpha:1.0]];
		}
	}else if([[aNotification object] isEqualTo:allMetamagicFeats]){
		NSManagedObject *feat=[availableFeats objectAtIndex:[allMetamagicFeats selectedRow]];
		if([chosenFeats containsObject:feat]){
			[addToChosenButton setEnabled:NO];
		}else{
			[addToChosenButton setEnabled:[self checkWhetherFeatCanBeAdded:feat]];
		}
	}
}
-(IBAction)xValueChanged:(id)sender{
	NSManagedObject *feat=[chosenFeats objectAtIndex:[chosenMetamagicFeats selectedRow]];
	int newXValue=[xValueTF intValue];
	int oldXValue=[[feat valueForKey:@"xValue"] intValue];
	if([[feat valueForKey:@"spellKey"] isEqualToString:@"Caster Level"]){
		int calInt=[castAtLevel intValue];
		if(newXValue-oldXValue+calInt<minCastLevel){
			int xValue2=oldXValue+minCastLevel-calInt;
			[xValueTF setIntValue:xValue2];
			[castAtLevel setIntValue:minCastLevel];
			[feat setValue:[NSNumber numberWithInt:xValue2]
					forKey:@"xValue"];
		}else if(newXValue-oldXValue+calInt<=maxCastLevel){
			[feat setValue:[NSNumber numberWithInt:newXValue]
					forKey:@"xValue"];
			[castAtLevel setIntValue:calInt+newXValue-oldXValue];
		}else{
			int xValue2=maxCastLevel-calInt+oldXValue;
			[xValueTF setIntValue:xValue2];
			[castAtLevel setIntValue:maxCastLevel];
			[feat setValue:[NSNumber numberWithInt:xValue2]
					forKey:@"xValue"];
		}
	}else{
		[feat setValue:[NSNumber numberWithInt:newXValue]
				forKey:@"xValue"];
	}
}
	//table properties.
-(int)numberOfRowsInTableView:(NSTableView *)aTableView{
	if([aTableView isEqualTo:allMetamagicFeats]){
		return [availableFeats count];
	}else if([aTableView isEqualTo:chosenMetamagicFeats]){
		return [chosenFeats count];
	}
	return 0;
}
-(id)tableView:(NSTableView *)aTableView
objectValueForTableColumn:(NSTableColumn *)aTableColumn
		   row:(int)row{
	if([aTableView isEqualTo:allMetamagicFeats]){
		return [[availableFeats objectAtIndex:row] valueForKey:@"name"];
	}else if([aTableView isEqualTo:chosenMetamagicFeats]){
		return [[chosenFeats objectAtIndex:row] valueForKey:@"name"];
	}
	return nil;
}
@end
